<?php

namespace App\Controller\Home;

use App\Controller\Example\UserExample;
use App\Models\ConfigModel;
use App\Models\Conn;
use App\Models\CtcSettingModel;
use App\Models\UsersModel;
use Config\Config;
use Core\Common\Common;
use Core\Enums\DigitEnum;
use Core\Enums\FundsEnum;
use Core\Utils\Utils;

class AutoLinglongSett
{
    /**灵龙商城自动领取
     * TODO 积分领取(自动)
     * @param $data
     * return void
     * */
    public function AutoSettCollectSaleReward(){
        $time = time();
        $startTime = strtotime(date('Y-m-d') . '23:30:00');
        $endTime = strtotime(date('Y-m-d') . '23:58:00');
        //if ($time >= $endTime || $time <= $startTime) Result::error("未到自动领取时间");
        echo "开始".date('h:i:s')."\r\n";
        $queryMemberSql="SELECT `id`,`token` FROM `users` WHERE `collect` = 0 and `ach` > 0 and `is_get` = 1 AND `id` > 20000 ORDER BY id DESC";
        $conn = new Conn();
        $readConn = $conn->readConn($queryMemberSql, true);
        $conn->close();
        $ids ='';
        foreach ($readConn as $value){
            $ids .= $value["id"].",";
            self::collectSaleReward($value["token"]);
        }
        if($ids ==''){
            echo "没有可领取积分"."\r\n";
        }else{
            echo "领取成功:".$ids."\r\n";
        }
        echo "结束".date('h:i:s')."\r\n";
        exit("执行完成");
    }
    /**
     * TODO 分享积分领取(自动)
     * @param $data
     * return void
     * */
    public function AutoSettCollectWinningReward(){
        $time = time();
        $startTime = strtotime(date('Y-m-d') . '23:50:00');
        $endTime = strtotime(date('Y-m-d') . '23:58:00');
        //if ($time >= $endTime || $time <= $startTime) Result::error("未到自动领取时间");
        echo "开始".date('h:i:s')."\r\n";
        $queryMemberSql="SELECT `id`,`token` FROM `users` WHERE `caigou` = 0 and `ach` > 0 and `sach` > 0 and `is_get` = 1 AND `id` > 20000 ORDER BY id DESC";
        $conn = new Conn();
        $readConn = $conn->readConn($queryMemberSql, true);
        $conn->close();
        $ids ='';
        foreach ($readConn as $value){
            $ids .= $value["id"].",";
            self::collectWinningReward($value["token"]);
        }
        if($ids ==''){
            echo "没有可领取积分"."\r\n";
        }else{
            echo "领取成功:".$ids."\r\n";
        }
        echo "结束".date('h:i:s')."\r\n";
        exit("执行完成");
    }
    /**
     * TODO 积分领取
     * @param $data
     * return void
     * */
    public static function collectSaleReward($token){
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $token);
        $UserExample = Common::assemble(new UserExample(), $userInside);
        $sn = Utils::createOrderNo();
        $reckonStatic = self::reckonStatic($conn, $userInside);
        if($reckonStatic > 0){
            $conn->shiwuStart();
            $balance = $UserExample->money + $reckonStatic;
            $editUserMoneyAddInside = UsersModel::editUserSalesInside($conn, $reckonStatic, $UserExample);
            $writeFundsMoney1 = Funds::writeFundsMoney($conn, $UserExample->id, $sn, FundsEnum::COMMISSION, $reckonStatic, $balance, "系统".FundsEnum::COMMISSIONZHCN);
            $writeFundsSale = Funds::writeFundsSale($conn, $UserExample->id, $sn, FundsEnum::COMMISSION, -$reckonStatic, 0, "系统".FundsEnum::COMMISSIONZHCN);
            if($editUserMoneyAddInside > DigitEnum::ONE || $writeFundsMoney1 != DigitEnum::ONE || $writeFundsSale != DigitEnum::ONE){
                $conn->shiwuRollback();
                $content = "领取失败-Y=>用户id：".$UserExample->id.",奖励：".$reckonStatic.",时间：".date("Y-m-d H:i:s",time());
                Utils::writeSettLog($content);
                echo "领取失败-Y"."\r\n";
                return false;
            }
            $totalReward = $UserExample->ach;
            $moneyPrice = self::getMoneyPrice($conn);
            $UserExampleAllPid = UsersModel::getUserSuperiorAllPid($conn, $UserExample->pid);
            $rewardPro = $maxLevel = $peerLevel = $yguanli =0;
            $peer = true;
            foreach ($UserExampleAllPid as $value){
                $UserExampleAll = Common::assemble(new UserExample(), $value);
                //极差奖励
                /*1星 0.00045
                  2星 0.0009
                  3星 0.0012
                  4星 0.0015
                  5星 0.0018
                  6星 0.0021
                  7星 0.0024
                  平级 0.00015
                 * */
                if($value["level"] > $maxLevel){
                    $levelScale = self::getLevelScale($conn, $value["level"]);
                    $peerScale = self::getPeerScale($conn);
                    $guanliNum = $value["level"] - 1 - $peerLevel - $yguanli;
                    $guanli = $guanliNum * $peerScale * $totalReward / $moneyPrice;
                    $scale = $levelScale - $rewardPro;
                    if($guanli > DigitEnum::MINIMUM){
                        $yguanli +=$guanliNum;
                        $Reward = $totalReward * $scale / $moneyPrice + $guanli;
                    }else{
                        $Reward = $totalReward * $scale / $moneyPrice;
                    }
                    if($Reward > DigitEnum::MINIMUM){
                        $editUserMoneyAddInside = UsersModel::editUserAgentInside($conn, $Reward, $UserExampleAll);
                        $writeFundsPrize = Funds::writeFundsBonus($conn, $UserExampleAll->id, $sn, FundsEnum::EXPANDPOINTREWARDS, $Reward, $UserExampleAll->agent_reward+$Reward, FundsEnum::EXPANDPOINTREWARDSZHCN);
                        if($editUserMoneyAddInside != DigitEnum::ONE || $writeFundsPrize != DigitEnum::ONE){
                            $conn->shiwuRollback();
                            $content = "领取失败-J=>用户id：".$UserExampleAll->id.",奖励：".$Reward.",时间：".date("Y-m-d H:i:s",time());
                            Utils::writeSettLog($content);
                            echo "领取失败-J"."\r\n";
                            return false;
                        }
                    }
                    $rewardPro = $rewardPro + $scale;
                    $peer = true;
                }
                //平级奖励
                if($peer && $value["level"] > 0 && $value["level"] == $maxLevel){
                    $peerReward = $totalReward * self::getPeerScale($conn) / $moneyPrice;
                    if($Reward > DigitEnum::MINIMUM){
                        $editUserMoneyAddInside = UsersModel::editUserAgentInside($conn, $peerReward, $UserExampleAll);
                        $writeFundsPrize = Funds::writeFundsBonus($conn, $UserExampleAll->id, $sn, FundsEnum::EXPANDPOINTREWARDS, $peerReward, $UserExampleAll->agent_reward+$peerReward, FundsEnum::EXPANDPOINTREWARDSZHCN);
                        if($editUserMoneyAddInside != DigitEnum::ONE || $writeFundsPrize != DigitEnum::ONE){
                            $conn->shiwuRollback();
                            $content = "领取失败-P=>用户id：".$UserExampleAll->id.",奖励：".$Reward.",时间：".date("Y-m-d H:i:s",time());
                            Utils::writeSettLog($content);
                            echo "领取失败-P"."\r\n";
                            return false;
                        }
                    }
                    $peerLevel += 1;
                    $peer = false;
                }
                if($value["level"] > $maxLevel){
                    $maxLevel = $value["level"];
                }
            }
            $conn->shiwuEnd();
        }
    }
    /**
     * TODO 分享积分领取
     * @param $data
     * return void
     * */
    public static function collectWinningReward($token){
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $token);
        $UserExample = Common::assemble(new UserExample(), $userInside);
        $sn = Utils::createOrderNo();
        $conn->shiwuStart();
        $reckonDirect = self::reckonDirect($conn,$userInside);
        if($reckonDirect > 0){
            $totalMoney = $reckonDirect;
            $balance = $UserExample->money + $totalMoney;
            $editUserMoneyAddInside = UsersModel::editUserWinningInside($conn, $totalMoney, $UserExample);
            $writeFundsMoney = Funds::writeFundsMoney($conn, $UserExample->id, $sn, FundsEnum::WINNINGBENEFITS, $totalMoney, $balance, "系统".FundsEnum::WINNINGBENEFITSZHCN);
            $writeFundsPrize = Funds::writeFundsPrize($conn, $UserExample->id, $sn, FundsEnum::WINNINGBENEFITS, -$totalMoney, 0, "系统".FundsEnum::WINNINGBENEFITSZHCN);
            if($editUserMoneyAddInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE || $writeFundsPrize != DigitEnum::ONE){
                $conn->shiwuRollback();
                $content = "领取失败-F=>用户id：".$UserExample->id.",奖励：".$totalMoney.",时间：".date("Y-m-d H:i:s",time());
                Utils::writeSettLog($content);
                echo "领取失败-F"."\r\n";
                return false;
            }
        }
        $conn->shiwuEnd();
    }
    /**
     * TODO 静态奖励计算
     * @param $data
     * return void
     * */
    public static function reckonStatic($conn,$userInside){
        $moneyPrice = self::getMoneyPrice($conn);
        $jingtai = ConfigModel::getConfigSingleValName($conn, Config::SMALL_REWARD);//静态奖励比例
        $jiangli = 0;
        if($userInside["id"] == 108776){//总账号增加收益
            $jiangli = $userInside["sach"] * 0.0008333 / $moneyPrice;;
        }
        if($userInside["ach"] > 0 && $userInside["collect"] == 0){
            return $jiangli + $userInside["ach"] * $jingtai / $moneyPrice;
        }else{
            return 0;
        }
    }
    /**
     * TODO 直推奖励计算
     * @param $data
     * return void
     * */
    public static function reckonDirect($conn,$userInside){
        $userInside["zach"] = UsersModel::getUserAllAchPid($conn, $userInside["id"]);
        $moneyPrice = self::getMoneyPrice($conn);
        $zhitui = ConfigModel::getConfigSingleValName($conn, Config::BIG_REWARD);//直推奖励比例
        if($userInside["zach"] > 0 && $userInside["caigou"] == 0){
            return $userInside["zach"] * $zhitui / $moneyPrice;
        }else{
            return 0;
        }
    }
    /**
     * TODO 获取当前消费积分价格
     * @param $data
     * return void
     * */
    public static function getMoneyPrice($conn){
        return CtcSettingModel::getCtcSettingInit($conn, 2)["consult_price"];
    }
    /**
     * TODO 获取用户星级奖励比例
     * @param $data
     * return void
     * */
    public static function getLevelScale($conn,$level){
        switch ($level){
            case 1 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_1);break;
            case 2 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_2);break;
            case 3 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_3);break;
            case 4 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_4);break;
            case 5 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_5);break;
            case 6 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_6);break;
            case 7 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_7);break;
            default:$scale = 0;break;
        }
        return $scale;
    }
    /**
     * TODO 获取用户平级奖励比例
     * @param $data
     * return void
     * */
    public static function getPeerScale($conn){
        return ConfigModel::getConfigSingleValName($conn, Config::PROCURE_FEE);
    }
}